package com.example.provider.service.impl;

import com.example.common.entity.Bidding;
import com.example.common.entity.Demand;
import com.example.common.entity.Message;
import com.example.common.entity.WorkRoom;
import com.example.provider.dao.BiddingDao;
import com.example.provider.dao.WorkroomApplyDao;
import com.example.provider.dao.WorkroomDao;
import com.example.provider.service.WorkroomService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class WorkroomServiceImpl implements WorkroomService {
    @Autowired
    private WorkroomApplyDao workroomApplyDao;
    @Autowired
    private BiddingDao biddingDao;
    @Autowired
    private WorkroomDao workroomDao;
    
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    //工作室注册
    @Transactional
    public Message applyWorkroom(WorkRoom workRoom) {
        WorkRoom  workRoo= workroomApplyDao.findWorkroomByName(workRoom.getWorkroomName());
        if(workRoo!=null) {
            return  new Message(300,"用户名存在");
        }else{
            workroomApplyDao.insertWorkroom(workRoom);
            return new Message(800,"成功");
        }
    }

    /**
     * 根据工作室id搜索对应的竞标情况
     * @param id
     * @return
     */
    public List<Demand> checkBidding(int id) throws IOException {
        //1、从数据库中搜出对应的竞标列表
        List<Bidding> biddings = biddingDao.searchByWorkroomId(id);

        //2、根据组号去寻找对应的需求，并把状态赋给需求
        List<Demand> demands = new ArrayList<>();
        SearchRequest request = new SearchRequest("demo_demand");
        //构建搜索条件
        SearchSourceBuilder builder = new SearchSourceBuilder();
        for (Bidding bidding : biddings) {
            TermQueryBuilder queryBuilder =
                    QueryBuilders.termQuery("id", bidding.getGroupId());
            builder.query(queryBuilder);
            request.source(builder);
            SearchResponse response =
                    restHighLevelClient.search(request, RequestOptions.DEFAULT);
            Map map = response.getHits().getAt(0).getSourceAsMap();
            Demand d = new Demand((int)map.get("id"), map.get("lable").toString(),
                    (double)map.get("money"), map.get("phone").toString(),
                    map.get("description").toString());
            //从竞标状况中去取状态
            d.setStatus(bidding.getStates());
            demands.add(d);
        }
        return demands;
    }

    /**
     * 根据当前用户id寻找工作室用户id
     * @param id 当前登录用户id
     * @return
     */
    public int searchWIdById(int id) {
        return workroomDao.searchByIdd(id).getId();
    }

    //通过工作室id和组号删除竞标关系
    public Message deleteBidding(int workroomId, long groupId) {
        biddingDao.deleteByWIdAndGId(workroomId, groupId);
        return new Message(200, "删除成功");
    }

    //通过当前用户id取出工作室
    public WorkRoom searchWorkroomByIdd(int idd) {
        return workroomDao.searchByIdd(idd);
    }

    /**
     * 给工作室对于这次竞标评个分
     * @param bidding
     * @return
     */
    public double getGrade(Bidding bidding) throws IOException {
        //1、工作室的lable和需求的lable重合之处，需求lable为主，重合数量占总数量的百分比
        //1)、取出需求lable
        SearchRequest request = new SearchRequest("demo_demand");
        //构建搜索条件
        SearchSourceBuilder builder = new SearchSourceBuilder();
        TermQueryBuilder queryBuilder =
                QueryBuilders.termQuery("id", bidding.getGroupId());
        builder.query(queryBuilder);
        request.source(builder);
        SearchResponse response =
                restHighLevelClient.search(request, RequestOptions.DEFAULT);
        String dLable = new String();
        for (SearchHit hit : response.getHits().getHits()) {
            Map map = hit.getSourceAsMap();
            dLable = map.get("lable").toString();
        }
        String[] dLables;
        if(dLable.contains(",")){
            //2)、按逗号分割成数组
            dLables = dLable.split(",");
        }
        else{
            dLables = new String[1];
            dLables[0] = dLable;
        }

        //3)、取出工作室lable
        WorkRoom workRoom = workroomDao.searchById(bidding.getWorkroomId());
        String wLable = workRoom.getLable();
        String[] wLables;
        if(wLable.contains(",")){
            //4)、按逗号分割成数组
            wLables = wLable.split(",");
        }
        else{
            wLables = new String[1];
            wLables[0] = wLable;
        }

        //5)、循环判断重合的次数
        int cnt = 0;
        for (String dl : dLables) {
            for (String wl : wLables) {
                if (dl.equals(wl)){
                    cnt++;
                }
            }
        }

        //6)、计算标签部分最后的分数
        double lableScore = cnt * 1.0 / dLables.length * 50;

        //2、工作室本身的评分占一半
        double grade = workRoom.getGrade() / 2;
        return lableScore + grade;
    }

    /**
     * 添加竞标关系
     * @param bidding 竞标关系
     * @return
     */
    @Transactional
    public Message addBidding(Bidding bidding) {
        biddingDao.insertBidding(bidding);
        return new Message(200, "申请成功");
    }

    /**
     * 根据工作室id查看工作室信息
     * @param id 工作室id
     * @return
     */
    public WorkRoom checkById(int id) {
        return workroomDao.searchById(id);
    }
}
